﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using Caliburn.PresentationFramework.Views;

namespace MTGenome.UI
{
    public interface IText
    {
        bool IsText
        {
            get;
        }
    }

    public static class TextBlockBehavior
    {
        #region ItemsSource

        /// <summary>
        /// ItemsSource Attached Dependency Property
        /// </summary>
        public static readonly DependencyProperty ItemsSourceProperty =
            DependencyProperty.RegisterAttached("ItemsSource", typeof(IEnumerable), typeof(TextBlockBehavior),
                new FrameworkPropertyMetadata((IEnumerable)null,
                    new PropertyChangedCallback(OnItemsSourceChanged)));

        /// <summary>
        /// Gets the ItemsSource property.  This dependency property 
        /// indicates a collection to bind to an InlineCollection via Caliburn.
        /// </summary>
        public static IEnumerable GetItemsSource(DependencyObject d)
        {
            return (IEnumerable)d.GetValue(ItemsSourceProperty);
        }

        /// <summary>
        /// Sets the ItemsSource property.  This dependency property 
        /// indicates a collection to bind to an InlineCollection via Caliburn.
        /// </summary>
        public static void SetItemsSource(DependencyObject d, IEnumerable value)
        {
            d.SetValue(ItemsSourceProperty, value);
        }

        /// <summary>
        /// Handles changes to the ItemsSource property.
        /// </summary>
        private static void OnItemsSourceChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            TextBlock text = d as TextBlock;
            if (text != null)
            {
                text.Inlines.Clear();

                IEnumerable list = e.NewValue as IEnumerable;
                if (list != null)
                {
                    foreach (object item in list)
                    {
                        IText itext = item as IText;
                        if (itext != null && itext.IsText)
                        {
                            text.Inlines.Add(itext.ToString());
                        }
                        else
                        {
                            var control = new ContentControl();
                            View.SetModel(control, item);
                            text.Inlines.Add(new InlineUIContainer(control));
                        }
                    }
                }
            }
        }

        #endregion
    }
}
